import router from './router'
import {ElMessage} from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {getToken} from '@/utils/auth'
import {isHttp} from '@/utils/validate'
import {isRelogin} from '@/utils/request'
import useLoginUserStore from '@/store/modules/user'
import useSettingsStore from '@/store/modules/settings'
import usePermissionStore from '@/store/modules/permission'

NProgress.configure({showSpinner: false});
//放行url的白名单：'/adminseal.zz' 为印章服务地址
const whiteList = ['/login', '/adminseal.zz'];
const apiUrl = import.meta.env.VITE_APP_BASE_API

router.beforeEach(async (to, from, next) => {
    //进度条
    NProgress.start()
    if (whiteList.indexOf(to.path) >= 0) {
        if (to.path === '/adminseal.zz') {
            //登录电子签章简易平台时访问地址拼接上代理名称后重定向
            location.href = apiUrl + to.path
        } else {
            // 在免登录白名单，直接进入
            next()
        }
    } else if (!getToken()) {
        // 没有token
        next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
        NProgress.done()
    } else {
        /* has token*/
        to.meta.title && useSettingsStore().setTitle(to.meta.title)
        if (to.path === '/login') {
            next({path: '/'})
            NProgress.done()
        } else {
            if (useLoginUserStore().permissions.length > 0) {
                isRelogin.show = true
                //有权限，直接放行
                next()
            } else {
                isRelogin.show = false
                try {
                    // 判断当前用户是否已拉取完user_info信息
                    await useLoginUserStore().getLoginUserInfo()
                    //获取动态路由
                    let accessRoutes = await usePermissionStore().generateRoutes()
                    accessRoutes.forEach(route => {
                        if (!isHttp(route.path)) {
                            // 动态添加可访问路由表
                            router.addRoute(route)
                        }
                    })
                    next({ ...to, replace: true })
                } catch (error) {
                    await useLoginUserStore().logOut()
                    ElMessage.error(error)
                    next({path: '/'})
                }
            }
        }
    }
})

router.afterEach(() => {
    NProgress.done()
})
